<?php


namespace app\community\controller;


use app\common\controller\Together;
use app\common\controller\Common;
use app\index\controller\Base;
use think\Config;
use think\Db;
use think\Exception;
use think\Session;
use think\Validate;

class Party extends Base
{

    //党员列表
    public function index(){
        $keyword = '';
        $classify_id = '';
        $where = [];
        if (!empty($_GET['keyword'])) {
            $keyword = $_GET['keyword'];
            $where['a.name'] = ['like', "%{$keyword}%"];
        }
        if(!empty($_GET['classify_id'])){
            $classify_id = $_GET['classify_id'];
            $where['a.classify_id'] = $classify_id;
        }
        $thisWechat = Session::get("thisWechat");
        $where['b.uniacid'] = $thisWechat['id'];

        if (!empty($_GET['type'])) {
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("community_record")->alias("a")
                    ->join("community_colony b", "a.colony_id = b.id")
                    ->where($where)->field("a.*,b.name colony_name")->limit($start,$limit)->select();
                $count = Db::name("community_record")->alias("a")
                    ->join("community_colony b", "a.colony_id = b.id")
                    ->where($where)->count("*");

                //审核状态
                $audit = Db::name("config_attribute")->where(['key' => "audit"])->value("value");
                $audit = explode("|", $audit);
                foreach ($audit as $k => $v) {
                    $audit[$k + 1] = $v;
                }
                unset($audit[0]);
                $sex = Db::name("config_attribute")->where(['key' => "sex"])->value("value");
                $sex = explode("|", $sex);
                foreach ($sex as $k => $v) {
                    $sex[$k + 1] = $v;
                }
                unset($sex[0]);
                foreach ($list as $k => $v) {
                    //$list[$k]['status'] = $audit[$v['status']];
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                    $v['faceUrl'] = empty($v['faceUrl']) ? "/static/images/nopic-107.png" : $v['faceUrl'];
                    $list[$k]['faceUrl'] = "<img src='".$v['faceUrl']."' style='max-height:50px;max-width:50px;'>";
                    $list[$k]['sex'] = $sex[$v['sex']];
                }
                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            } catch (Exception $e) {
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }


        $assign = [
            'keyword' => $keyword,
            'classify_id'=>$classify_id
        ];
        $this->assign($assign);
        return $this->fetch('index');
    }

    //充值操作
    public function changes(){
        $type = $_POST['type'];
        $id = $_POST['id'];
        $common = new Common();
        try{
            $status = $_POST['status']; //操作
            $number = $_POST['number']; //数量
            $remark = empty($_POST['remark'])?'':$_POST['remark']; //备注

            $integral = Db::name("community_record")->where(['id'=>$id])->value("integral");
            if($number<0){
                throw new Exception("非法操作");
            }
            if($status==2){
                if($integral - $number<0){ throw new Exception("非法操作");}
                Db::name("community_record")->where(['id'=>$id])->setDec("integral",$number);
                $after_number = $integral-$number;
                $log['remark'] = "用户【" . Session::get("user_name") . "】操作党员积分,积分减少【".$number."】,操作党员id【".$id."】";
            }elseif ($status==1){
                Db::name("community_record")->where(['id'=>$id])->setInc("integral",$number);
                $log['remark'] = "用户【" . Session::get("user_name") . "】操作党员积分,积分增加【".$number."】,操作党员id【".$id."】";
                $after_number = $integral+$number;
            }else{
                Db::name("community_record")->where(['id'=>$id])->update(['integral'=>$number]);
                $log['remark'] = "用户【" . Session::get("user_name") . "】操作党员积分,最终积分【".$number."】,操作党员id【".$id."】";
                $after_number = $number;
            }


            //记录日志
            $data['remark'] = $remark;
            $data['reg_id'] = $id;
            $data['type'] = "integral";
            $data['type_status'] = $status;
            $data['number'] = $number;
            $data['before_number'] = $integral;
            $data['after_number'] = $after_number;
            $data['addtime'] = time();
            $data['operator_id'] = Session::get("id");
            $data['auto'] =  Session::get("auto");
            Db::name("community_record_log")->insert($data);


            //记录操作日志
            $log['controller'] = "Party";
            $log['methods'] = "changes";
            $common->addLog($log);

            $black['code'] = 0;
            $black['msg'] = "操作成功";
        }catch (Exception $e){
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
        }
        return $black;

    }

    //积分明细
    public function integralLog(){
        $where = [];

        if(empty($_GET['id'])){
            throw new Exception("非法操作");
        }
        $id = $_GET['id'];
        $this->assign('id',$id);
        $where['a.reg_id'] = $_GET['id'];


        if(!empty($_GET['type'])){
            try {
                $page = empty($_GET['page']) ? 1 : $_GET['page'];
                $limit = empty($_GET['limit']) ? 10 : $_GET['limit'];
                $start = ($page - 1) * $limit;
                $list = Db::name("community_record_log")->alias("a")
                    ->join("community_record b","a.reg_id = b.id")
                    ->field("a.*,b.name")
                    ->where($where)->limit($start,$limit)
                    ->order("a.id desc")
                    ->select();

                $type_status = [1=>"增加",2=>"减少",3=>"管理员设置"];
                foreach ($list as $k=>$v){
                    $list[$k]['status'] = $type_status[$v['type_status']];
                    $list[$k]['type'] = "积分";
                    $list[$k]['addtime'] = date("Y-m-d H:i:s",$v['addtime']);
                }

                $count = Db::name("community_record_log")->alias("a")
                    ->join("community_record b","a.reg_id = b.id")
                    ->where($where)->count("*");

                $black['code'] = 0;
                $black['data'] = $list;
                $black['count'] = $count;
            }catch (Exception $e){
                $black['code'] = 202;
                $black['msg'] = $e->getMessage();
            }
            return $black;
        }

        return $this->fetch('log');
    }


    //档案模型字段
    public function record(){
        //审核状态
        $audit = Db::name("config_attribute")->where(['key' => "audit"])->value("value");
        $audit = explode("|", $audit);
        foreach ($audit as $k => $v) {
            $audit[$k + 1] = $v;
        }
        unset($audit[0]);
        //性别
        $sex = Db::name("config_attribute")->where(['key' => "sex"])->value("value");
        $sex = explode("|", $sex);
        foreach ($sex as $k => $v) {
            $sex[$k + 1] = $v;
        }
        unset($sex[0]);
        //身体状况
        $condition = Db::name("config_attribute")->where(['key' => "condition"])->value("value");
        $condition = explode("|", $condition);
        foreach ($condition as $k => $v) {
            $condition[$k + 1] = $v;
        }
        unset($condition[0]);
        //学历
        $schooling = Db::name("config_attribute")->where(['key' => "schooling"])->value("value");
        $schooling = explode("|", $schooling);
        foreach ($schooling as $k => $v) {
            $schooling[$k + 1] = $v;
        }
        unset($schooling[0]);
        //义工类型
        $volunteers = Db::name("config_attribute")->where(['key' => "volunteers"])->value("value");
        $volunteers = explode("|", $volunteers);
        foreach ($volunteers as $k => $v) {
            $volunteers[$k + 1] = $v;
        }
        unset($volunteers[0]);
        //获取所管理的景区
        //获取管理的景区
        $Together = new Together();
        $colony = $Together->findColony();

        //星级
        $level = Config::get("level");
        //党员身份
        $account = Config::get("account");
        //查询档案模型栏目 $colony[0]['id']
        $classify = Db::name("community_article_classify")->where(['colony_id'=>$colony[0]['id'],'type'=>2])->select();
        $assign = [
            "colony"=>$colony,
            "audit" => $audit,
            "sex" => $sex,
            "condition" => $condition,
            "schooling" => $schooling,
            "volunteers" => $volunteers,
            "level"=>$level,
            "account"=>$account,
            "classify"=>$classify
        ];
        return $assign;
    }

    //添加党员
    public function addData(){
        $record = $this->record();
        $this->assign($record);
        $classify_id = empty($_GET['classify_id'])?0:$_GET['classify_id'];
        $this->assign("classify_id",$classify_id);
        if(empty($_GET['id'])){
            return $this->fetch('addData');
        }else{
            $id = $_GET['id'];
            $detail = Db::name("community_record")->alias("a")
                ->join("admin_fans b", "a.fans_id = b.id")
                ->where(['a.id' => $id])->field("a.*,b.realName")
                ->find();
            $detail['faceUrl'] = empty($detail['faceUrl'])?"/static/images/nopic-107.png":$detail['faceUrl'];


            $this->assign("detail", $detail);
            return $this->fetch('editData');
        }
    }

    //执行添加、修改操作
    public function doParty(){
        $common = new Common();
        Db::startTrans();
        try{
            $rule = [
//                ["fans_id", "require", "请关联粉丝"],
                ["colony_id", "require", "请选择所属景区"],
                ["classify_id", "require", "请关联栏目"],
                ["name", "require", "请输入党员姓名"],
                ["branch", "require", "请输入所属支部"],
//                ["birth", "require", "请输入出生年月"],
//                ["party_time", "require", "请输入入党时间"],
                ["faceUrl", "require", "请上传党员照片"],
                ["promise", "require", "任务认领情况不能为空"],
//                ["exponent", "require", "任务完成情况不能为空"],
//                ["content", "require", "请输入简介"],
            ];
            $validate = new Validate($rule);
            $value = $this->request->post();

            $thisWechat = Session::get("thisWechat");
            $value['uniacid'] = $thisWechat['id'];
            if (!$validate->check($value)) {
                throw new Exception($validate->getError());
            }

            //判断该志愿者在对应景区是否填表
            $where['fans_id'] = $value['fans_id'];
            $where['colony_id'] = $value['colony_id'];
//            $where['community_id'] = $value['community_id'];
            if (!empty($value['id'])) {
                $where['id'] = ['neq', $value['id']];
            }
            $detail = Db::name("community_record")->where($where)->value("id");
            /*if (!empty($detail)) {
                throw new Exception("该粉丝在该景区已存在党员信息，无需重复添加");
            }*/
            //执行添加操作
            if (empty($value['id'])) {
                $value['addtime'] = time();
                $value['add_id'] = Session::get("id");
                $id = Db::name("community_record")->insertGetId($value);
                $log['remark'] = "用户【" . Session::get("user_name") . "】录入党员信息,党员id【" . $id . "】";
            } else {
                $id = $value['id'];
                $value['updatetime'] = time();
                $value['update_id'] = Session::get("id");
                Db::name("community_record")->update($value);
                $log['remark'] = "用户【" . Session::get("user_name") . "】更新党员信息,党员id【" . $id . "】";
            }
            $log['controller'] = "Party";
            $log['methods'] = "doParty";
            $common->addLog($log);
            $black['code'] = 0;
            $black['msg'] = "添加成功";
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }

    //删除
    public function delParty(){
        $common = new Common();
        Db::startTrans();
        try {
            $id = $_POST['id'];
            $navList = Db::name("community_record")->where(['id' => ['in', $id]])->field("id,name")->select();
            $navList = array_column($navList, "id");
            $navList = implode($navList, ",");
            $log['remark'] = "账号【" . Session::get("user_name") . "】删除志愿者信息,删除id【" . $navList . "】";
            $log['controller'] = "Party";
            $log['methods'] = "delParty";
            $common->addLog($log);
            Db::name("community_record")->where(['id' => ['in', $id]])->delete();
            $black['code'] = 0;
            $black['msg'] = "删除成功";
            Db::commit();
        } catch (Exception $e) {
            $black['code'] = 202;
            $black['msg'] = $e->getMessage();
            Db::rollback();
        }
        return $black;
    }


}